package com.xuecheng.order.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.constants.OrdersConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.order.config.PayTemplate;
import com.xuecheng.order.domain.Orders;
import com.xuecheng.order.domain.Payment;
import com.xuecheng.order.mapper.PaymentMapper;
import com.xuecheng.order.service.OrdersService;
import com.xuecheng.order.service.PaymentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 订单支付信息 服务实现类
 * </p>
 *
 * @author HuangYuwu
 * @since 2022-09-16
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements PaymentService {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private PayTemplate payTemplate;
    /**
     * 生成支付链接
     * @param orderNo
     * @return
     */
    @Override
    public ResponseResult createPay(String orderNo) {
        LambdaQueryWrapper<Orders>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getOrderNo,orderNo);
        Orders orders = ordersService.getOne(queryWrapper);
        Integer status = orders.getStatus();
        if (!status.equals(OrdersConstants.ORDER_INIT_STATUS)){
            throw new BusinessException(ErrorCode.PAYERROR);
        }
        //查询是否有未提交订单 TODO 超时未支付订单 生成新订单
        LambdaQueryWrapper<Payment>lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Payment::getOrderNo,orderNo);
        Payment payment = this.getOne(lambdaQueryWrapper);
        if (payment == null){
            payment=new Payment();
            payment.setUserName(orders.getUserName());
            payment.setUserId(orders.getUserId());
            payment.setCompanyId(orders.getCompanyId());
            payment.setOrderNo(orderNo);
            payment.setStatus(String.valueOf(OrdersConstants.NOT_PAID));
            payment.setPayMethod(OrdersConstants.PAY_METHOD_WX);
            payment.setCreateDate(DateUtil.date());
            payment.setTotalAmount(orders.getPrice());
            this.save(payment);
        }
        String url = payTemplate.createOrder(orderNo, payment.getTotalAmount(), orders.getCoursePubName());
        return ResponseResult.okResult(url);
    }
}
